#encoding: utf-8
class CertificatesController < ApplicationController
  before_filter :set_certificate

  def set_certificate
    @certificate = true
  end

  def create
    begin
      @certificate = Sertificate.new(params.except(:action, :controller))
      @certificate.price.gsub!(/[\sР\.]/, '')
      if(params[:date_send])
        @certificate.date_send.gsub!('•', '/')
      end

      respond_to do |format|
        if @certificate.save
          daily_index = Sertificate.where('created_at >= ? AND created_at < ? ', @certificate.created_at.to_date, @certificate.created_at).count + 1
          id = @certificate.id + 900000
          date = @certificate.created_at.strftime("%d%m%Y")
          number = "#{id}#{date}#{daily_index}"
          @certificate.order = number
          @certificate.save
          CertificateMailer.new_certificate(@certificate).deliver
          format.html { render json: {'success'=>true,
                                      'certificate' => {
                                          'number' => number,
                                          'amount' => @certificate.price,
                                          'email' => @certificate.email,
                                          'phone' =>@certificate.phone
                                      }
          } }
        else
          format.html { render json: {'success'=>false, 'error' => null} }
        end
      end
    rescue Exception => e
      respond_to do |format|
        format.html { render json: {'success' => false, 'error'=>e.message} }
      end
    end
  end

  def confirm
    begin
      id = params[:ordernumber]
      cert = Sertificate.where(order: id).first
      secret = "coco"
      glue = params[:merchant_id]+id + params[:amount]+params[:currency]+params[:orderstate]
      hash = Digest::MD5.hexdigest((Digest::MD5.hexdigest(secret) + Digest::MD5.hexdigest(glue)).upcase).upcase
      if hash == params[:checkvalue] && cert.price.to_i == params[:amount].to_i
        cert.paid = true
        cert.save
        CertificateMailer.certificate_paid(cert.order).deliver
        if cert.kind == 'virtual'
          CertificateMailer.certificate(cert).deliver
        end
        respond_to do |format|
          format.html { render nothing: true }
        end
      end
    rescue Exception => e
      respond_to do |format|
        format.html { render json: {'msg' =>e.message} }
      end
    end
  end

end
